package com.sunshine.schedulegrid.view

import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.sunshine.schedulegrid.R
import com.sunshine.schedulegrid.bean.CourseBean
import com.sunshine.schedulegrid.config.ScheduleConfig
import com.sunshine.schedulegrid.utils.ColorUtils
import com.sunshine.schedulegrid.utils.CourseList
import java.util.*
import kotlin.collections.ArrayList

/**
 * @author sunshine
 * @date 2020/8/29
 * 日程格子根布局
 */
class ScheduleView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, sc: ScheduleConfig? = null, courseList: CourseList? = null
) : LinearLayout(context, attrs, defStyleAttr){

    //日程格子配置类
    private var scheduleConfig: ScheduleConfig

    //日程列表
    private var courseList: CourseList

    //滑动布局
    private lateinit var weekSlideView: WeekSlideView

    init {
        //配置日程格子
        if (sc == null){
            scheduleConfig = ScheduleConfig()
            initXMLConfig(attrs)
        } else {
            scheduleConfig = sc
        }

        this.courseList = courseList ?: CourseList(scheduleConfig)

        init0()
    }

    /**
     * 把一些初始化分离出来方便设置参数时再调用
     */
    private fun init0() {
        weekSlideView = WeekSlideView(context, scheduleConfig = scheduleConfig, courseList = courseList, colorUtils = ColorUtils())
        initView()
    }

    /**
     * 初始化界面布局
     */
    private fun initView() {
        //重要！此处注意需要removeAllViews()，否则，当使用set方法设置配置或日程表时不会刷新
        removeAllViews()

        addView(weekSlideView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
    }

    /**
     * 获取布局文件中的配置
     * @param attrs
     * @return
     */
    private fun initXMLConfig(attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ScheduleView)
        val test = typedArray.getInt(R.styleable.ScheduleView_test, 1)
        typedArray.recycle()
    }

    fun setScheduleConfig(scheduleConfig: ScheduleConfig) {
        this.scheduleConfig = scheduleConfig
        //调用init0()来刷新界面
        init0()
    }

    fun setCourseList(courseList: CourseList) {
        this.courseList = courseList
        init0()
    }
}